package cn.tedu.spring.security.security;

import cn.tedu.spring.security.mapper.AdminMapper;
import cn.tedu.spring.security.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("用户名:{}",s);
        AdminLoginInfoVO adminLoginInfoVO = adminMapper.getStandardByUsername(s);
        if (adminLoginInfoVO == null){
            log.debug("没有此用户!");
            return null;
        }
        List<String> authoritiesList = adminLoginInfoVO.getPermissions();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String s1 : authoritiesList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(s1);
            authorities.add(simpleGrantedAuthority);
        }
        AdminDetails userDetails = new AdminDetails(
                adminLoginInfoVO.getId(),
                adminLoginInfoVO.getUsername(),
                adminLoginInfoVO.getPassword(),
                adminLoginInfoVO.getEnable()==1,
                authorities
        );
//        UserDetails userDetails = User.builder()
//                .username(s)
//                .password("123456")
//                .disabled(false)
//                .accountExpired(false)
//                .credentialsExpired(false)
//                .authorities("这是一个临时的权限")
//                .build();
        return userDetails;
    }
}
